package com.example.utils;

import com.example.entity.result.Result;
import com.example.exception.OperatorException;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 日期工具包
 */
public class DateUtils {

    private static final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static float diff = 0;

    public static String getLastUpdate() {
        return formatter.format(new Date());
    }

    public static float compare_date(String DATE1, String DATE2) {
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(DATE2);
            if (dt1.getTime() > dt2.getTime()) {
                diff = dt1.getTime() - dt2.getTime();
            } else if (dt1.getTime() < dt2.getTime()) {
                diff = dt2.getTime() - dt1.getTime();
            }
            return diff / 1000 / 60 / 60;
        } catch (Exception exception) {
            System.out.println(exception.getMessage());
        }
        return 0;
    }

    public static float compare_date_second(String DATE1, String DATE2) {
        diff = 0;
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(DATE2);
            diff = dt2.getTime() - dt1.getTime();
            return diff / 1000 / 60 / 60;
        } catch (Exception exception) {
            System.out.println(exception.getMessage());
        }
        return 0;
    }

    //格式化时间转化为时间戳
    public static Date Transfer(String time) {
        return parse(time, "yyyy-MM-dd HH:mm:ss");
    }

    public static Date parse(String time, String format) {
        DateFormat formatter = new SimpleDateFormat(format);
        try {
            return formatter.parse(time);
        } catch (ParseException e) {
            throw new OperatorException("时间解析异常", Result.PARAMETER_TYPE_ERROR);
        }
    }
}
